package cn.ihrm.sass.controller;

import cn.common.PageResult;
import cn.common.Result;
import cn.common.ResultCode;
import cn.controller.BaseController;
import cn.exception.CommonException;
import cn.ihrm.sass.entity.system.Role;
import cn.ihrm.sass.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

//解决跨域问题
@CrossOrigin

@Api(description = "角色管理",value = "RoleController")
@RestController
@RequestMapping(value = "/role")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    /**
     * 保存角色
     * @param role
     * @return
     */
    @ApiOperation(value = "保存角色")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Result save(@RequestBody Role role) {
        // 设置保存的企业id
        role.setCompanyId(companyId);
        //role.setCompanyName(companyName);

        //业务操作
        roleService.add(role);
        //return new Result(ResultCode.SUCCESS);
        return new Result(10000,"操作成功！",true);
    }

    /**
     * 根据id更新角色
     * 1.方法
     * 2.请求参数
     * 3.响应
     */
    @ApiOperation(value = "根据id更新角色")
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@PathVariable(value = "id") String id, @RequestBody Role role) {
        //业务操作
        role.setId(id);
        roleService.update(role);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据id删除角色
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id删除角色")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable(value = "id") String id) {
        roleService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据id查询角色
     * @param id
     * @return
     * @throws CommonException
     */
    @ApiOperation(value = "根据id查询角色")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable(value = "id") String id) throws CommonException {

        Role role = roleService.findById(id);
        Result result = new Result(ResultCode.SUCCESS);
        result.setData(role);
        return result;


        //throw new CommonException(ResultCode.UNAUTHORISE);
    }

    /**
     * 查询全部角色列表
     * @return
     */
    @ApiOperation(value = "查询全部角色列表")
    @RequestMapping(value = "findAll", method = RequestMethod.GET)
    public Result findAll(int page,int size,Role role) {
        //int i = 1 / 0;
        Page pageUser = roleService.findAll(companyId, page, size);
        //返回对象
        // 构造分页信息
        PageResult pageResult= new PageResult(pageUser.getTotalElements(),pageUser.getContent());
        Result result = new Result(ResultCode.SUCCESS,pageResult);
        return result;
    }
}
